package com.yonyou.sto.modules.ims.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.sto.common.api.CommonResult;
import com.yonyou.sto.modules.ims.dto.ImsPartySelectParam;
import com.yonyou.sto.modules.ims.mapper.ImsPartyMapper;
import com.yonyou.sto.modules.ims.model.ImsParty;
import com.yonyou.sto.modules.ims.service.ImsPartyService;
import com.yonyou.sto.modules.ums.model.UmsAdmin;
import com.yonyou.sto.modules.ums.service.UmsAdminService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author aegon
 * @since 2020-09-15
 */
@Service
public class ImsPartyServiceImpl extends ServiceImpl<ImsPartyMapper, ImsParty> implements ImsPartyService {

    @Resource
    private ImsPartyMapper imsPartyMapper;

    @Resource
    private UmsAdminService adminService;

    @Override
    public CommonResult create(ImsParty imsParty) {
        ImsParty sn = getPartyBySellerSn(imsParty.getSellerSn());
        if (!BeanUtil.isEmpty(sn)) return CommonResult.failed("收款单位编号重复");
        if (StrUtil.isNotBlank(imsParty.getVerifyUsername())) {
            UmsAdmin umsAdmin = adminService.getAdminByUsername(imsParty.getVerifyUsername());
            imsParty.setVerifyNickname(umsAdmin.getNickName());
        }
        imsParty.setCreateTime(new Date());
        imsParty.setStatus(1);
        imsParty.setSort(0);
        return CommonResult.success(save(imsParty));
    }

    @Override
    public boolean delete(Long id) {
        int size = getInvoiceSize(id);
        if (size == 0) {
            ImsParty imsParty = new ImsParty();
            imsParty.setId(id);
            imsParty.setStatus(0);
            imsPartyMapper.updateById(imsParty);
            return true;
        }
        return false;
    }

    @Override
    public int getInvoiceSize(Long id) {
        return imsPartyMapper.getInvoiceSize(id);
    }


    @Override
    public List<ImsPartySelectParam> getPartySelect() {
        QueryWrapper<ImsParty> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ImsParty::getStatus, 1);
        List<ImsParty> parties = list(wrapper);
        List<ImsPartySelectParam> params = new ArrayList<>();
        parties.forEach(imsParty -> {
            ImsPartySelectParam param = new ImsPartySelectParam();
            param.setPartyId(imsParty.getId());
            param.setPartyName(imsParty.getPartyName());
            params.add(param);
        });
        return params;
    }

    @Override
    public CommonResult importParty(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return CommonResult.failed("请上传excel2007版本及以上的xlsx文件");
        }

        try {
            XSSFWorkbook xssf = new XSSFWorkbook(file.getInputStream());
            int numberOfSheets = xssf.getNumberOfSheets();

            List<ImsParty> parties = new ArrayList<>();
            for (int i = 0; i < numberOfSheets; i++) {// 表
                XSSFSheet sheet = xssf.getSheetAt(i);
                int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
                for (int j = 0; j < physicalNumberOfRows; j++) {// 行
                    if (j == 0) continue;
                    XSSFRow row = sheet.getRow(j);
                    int physicalNumberOfCells = row.getPhysicalNumberOfCells();

                    ImsParty party = new ImsParty();
                    Field[] f = party.getClass().getDeclaredFields();

                    for (int k = 0; k < physicalNumberOfCells; k++) {// 单元格
                        row.getCell(k).setCellType(Cell.CELL_TYPE_STRING);
                        XSSFCell cell = row.getCell(k);
                        String stringCellValue = cell.getStringCellValue();
                        // 此方法要求导入格式必须正确 索引从1开始
                        String attributeName = f[k + 2].getName();
                        String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
                        Method setMethod = party.getClass().getMethod("set" + methodName, String.class);
                        setMethod.invoke(party, stringCellValue);

                        party.setCreateTime(new Date());
                        party.setStatus(1);
                    }
                    parties.add(party);
                }
            }
            boolean b = saveBatch(parties);
            return CommonResult.success("上传文件成功");
        } catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            return CommonResult.failed("上传文件格式不正确");
        }
    }

    @Override
    public ImsParty getPartyBySellerSn(String sellerSn) {
        return baseMapper.getPartyBySellerSn(sellerSn);
    }

    @Override
    public List<ImsParty> getPartyByVerifyUsername(String username) {
        return baseMapper.getPartyByVerifyUsername(username);
    }

    @Override
    public CommonResult getPartyByPartyId(List<Long> ids) {
        QueryWrapper<ImsParty> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ImsParty> lambda = wrapper.lambda();
        lambda.eq(ImsParty::getStatus, 1);
        lambda.in(ImsParty::getId,ids);
        List<ImsParty> imsParties = baseMapper.selectList(wrapper);
        return imsParties.size()==0?CommonResult.failed():CommonResult.success(imsParties);
    }


    @Override
    public Page<ImsParty> list(String keyword, Integer pageSize, Integer pageNum) {
        Page<ImsParty> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ImsParty> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ImsParty> lambda = wrapper.lambda();
        lambda.eq(ImsParty::getStatus, 1);
        if (StrUtil.isNotEmpty(keyword)) {
            lambda.like(ImsParty::getPartySn, keyword);
            lambda.or().like(ImsParty::getPartyName, keyword);
        }
        lambda.orderByDesc(ImsParty::getCreateTime);
        return page(page, wrapper);
    }

}
